package com.market.controller;

import com.market.entity.Bill;
import com.market.entity.Provider;
import com.market.service.BillService;
import com.market.service.ProviderService;
import com.market.utils.SessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/bill")
public class BillController {
    @Autowired
    private BillService billService;
    
    @Autowired
    private ProviderService providerService;

    /**
     * 获取所有账单列表
     */
    @GetMapping("/list")
    public Map<String, Object> list() {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Bill> bills = billService.findAll();
            result.put("flag", true);
            result.put("data", bills);
        } catch (Exception e) {
            result.put("flag", false);
            result.put("message", "获取账单列表失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 根据条件查询账单
     */
    @GetMapping("/search")
    public Map<String, Object> search(
            @RequestParam(required = false) String productName,
            @RequestParam(required = false) Long providerId,
            @RequestParam(required = false) Integer isPayment,
            @RequestParam(required = false) String billCode,
            @RequestParam(required = false, defaultValue = "1") Integer currentPage,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 使用分页查询
            com.market.utils.PageResult<Bill> pageResult = billService.findByConditionPage(
                    productName, providerId, isPayment, billCode, currentPage, pageSize);
            
            result.put("flag", true);
            result.put("data", pageResult.getList());
            result.put("total", pageResult.getTotalCount());
            result.put("currentPage", pageResult.getCurrentPage());
            result.put("pageSize", pageResult.getPageSize());
            result.put("totalPages", pageResult.getTotalPages());
        } catch (Exception e) {
            result.put("flag", false);
            result.put("message", "搜索账单失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 根据ID获取账单详情
     */
    @GetMapping("/{id}")
    public Map<String, Object> getById(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            Bill bill = billService.findById(id);
            if (bill != null) {
                result.put("flag", true);
                result.put("data", bill);
            } else {
                result.put("flag", false);
                result.put("message", "未找到ID为" + id + "的账单");
            }
        } catch (Exception e) {
            result.put("flag", false);
            result.put("message", "获取账单详情失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 添加账单
     */
    @PostMapping("/add")
    public Map<String, Object> add(@RequestBody Bill bill, HttpServletRequest request) {
        // 设置创建者为当前登录用户
        Long userId = SessionUtil.getCurrentUserId();
        if (userId != null) {
            bill.setCreatedBy(userId);
        }
        return billService.add(bill);
    }

    /**
     * 修改账单
     */
    @PutMapping("/update")
    public Map<String, Object> update(@RequestBody Bill bill, HttpServletRequest request) {
        // 设置修改者为当前登录用户
        Long userId = SessionUtil.getCurrentUserId();
        if (userId != null) {
            bill.setModifyBy(userId);
        }
        return billService.update(bill);
    }

    /**
     * 删除账单
     */
    @DeleteMapping("/delete/{id}")
    public Map<String, Object> delete(@PathVariable Long id) {
        return billService.deleteById(id);
    }
    
    /**
     * 获取所有供应商列表（用于账单管理中的供应商选择）
     */
    @GetMapping("/providers")
    public Map<String, Object> getProviders() {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Provider> providers = providerService.findAll();
            result.put("flag", true);
            result.put("data", providers);
        } catch (Exception e) {
            result.put("flag", false);
            result.put("message", "获取供应商列表失败: " + e.getMessage());
        }
        return result;
    }
}
